﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using MINERP.COM;
using System.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Threading;

namespace MINERP.UserLogin
{
    static class Program
    {
        static FrmUpdate _frmUpdate = null;
        public static string customerName;
        static List<string> list;
        static Dictionary<string, string> fontDictionary;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
         [HandleProcessCorruptedStateExceptions]
        [SecurityCritical]

        [STAThread]
        static void Main()
        {
            fontDictionary = new Dictionary<string, string>();
            fontDictionary.Add("C39HrP48DmTt", "C39HrP48DmTt.TTF");
            fontDictionary.Add("楷体", "simkai.ttf");
            fontDictionary.Add("Abri Barcode39", "BAR39.TTF");
            //MessageBox.Show("开始加密");

            //try
            //{
            //    UDPMessage.EncryptConfiguration();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("加密出错：" + ex.Message);
            //    return;
            //}

            //MessageBox.Show("加密结束");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException); 
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); 
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            bool bCreatedNew;
            Mutex m = new Mutex(false, "myUniqueNameaaaa", out bCreatedNew);

            if (bCreatedNew)
            {
#if !DEBUG
           list = UDPMessage.GetServerInfo();
                RegDLL();       
                PrepareSys();
                CheckFonts();
#endif

                Application.Run(new FrmLogin(list));
            }
            else
            {
                MessageBox.Show("本程序已运行，请不要重复打开");
            }
        }
         static void PrepareSys()
         {
             string sysDir = @"C:\WINDOWS\xmlData";
             if (!Directory.Exists(sysDir))
             {
                 Directory.CreateDirectory(sysDir);
             }

         }
        static void RegDLL()
        {
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "ImageEnXLibrary.ocx")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "ET199Com.dll")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "LayoutDll.dll")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "RealLayoutPanel.ocx")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "MarkImageDll.dll")));

        }
        private static void CheckFonts()
        {
            var fonts = System.Drawing.FontFamily.Families;
            foreach (KeyValuePair<string, string> kvp in fontDictionary)
            {

                if (fonts.FirstOrDefault(p => p.Name == kvp.Key) == null)
                {
                    string WinFontDir = System.Environment.GetEnvironmentVariable("windir") + "\\fonts";
                    string FontFileName = kvp.Value;
                    string FontName = kvp.Key;
                    int Ret;
                    int Res;
                    string FontPath;
                    const int WM_FONTCHANGE = 0x001D;
                    const int HWND_BROADCAST = 0xffff;
                    FontPath = WinFontDir + "\\" + FontFileName;
                    if (!File.Exists(FontPath))
                    {
                        File.Copy(System.Windows.Forms.Application.StartupPath + "\\" + FontFileName, FontPath);
                        Ret = AddFontResource(FontPath);

                        Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
                        Ret = WriteProfileString("fonts", FontName + "(TrueType)", FontFileName);
                    }
                }
            }
        }
        #region//DLL
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);


        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd, // handle to destination window 
        uint Msg, // message 
        int wParam, // first message parameter 
        int lParam // second message parameter 
        );

        [DllImport("gdi32")]
        public static extern int AddFontResource(string lpFileName);
        #endregion
        private static void UIThreadException(object sender, ThreadExceptionEventArgs t) 
        { 
            try 
            { 
                string errorMsg = "Windows窗体线程异常 : \n\n";
                WriteLogForCheck.WriteLogFile(DateTime.Now +":"+errorMsg + t.Exception.Message + Environment.NewLine + t.Exception.StackTrace);
            } 
            catch 
            { 
                MessageBox.Show("不可恢复的Windows窗体异常，应用程序将退出！"); 
            } 
        }        
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
        { 
            try 
            { 
                Exception ex = (Exception)e.ExceptionObject; 
                string errorMsg = "非窗体线程异常 : \n\n";
                WriteLogForCheck.WriteLogFile(DateTime.Now +":"+errorMsg + ex.Message + Environment.NewLine + ex.StackTrace); 
            } 
            catch 
            { 
                MessageBox.Show("不可恢复的非Windows窗体线程异常，应用程序将退出！"); 
            } 
        }
  
        static void UpdateVersion()
        {
            string currentVersion = GetCurrentVersion();
            string messageStr = list[0];
            string[] str = messageStr.Split('|');
            string newVersion = str[2];
            string updateFilePath = str[3];
            CloseUpdateForm();
            if (currentVersion != newVersion)
            {
                if (MessageBox.Show("程序检测到新版本,程序需要更新", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    Process.Start(updateFilePath);
                    Exit();
                }
            }
        }

        static string GetCurrentVersion()
        {
            string version = string.Empty;
            for (int i = 0; i < Assembly.GetExecutingAssembly().GetCustomAttributes(true).Length; i++)
            {

                if (Assembly.GetExecutingAssembly().GetCustomAttributes(true)[i] is AssemblyFileVersionAttribute)
                {
                    version = ((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(true)[i]).Version;
                }
            }
            return version;
        }

        static void KillEMProcess()//关闭所有正在运行的进程
        {
            System.Diagnostics.Process[] pTemp = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process pTempProcess in pTemp)
            {

                if ((pTempProcess.ProcessName.ToLower() == ("MINERP.UserLogin").ToLower()) || (pTempProcess.ProcessName.ToLower()) == ("MINERP.UserLogin.exe").ToLower())
                    pTempProcess.Kill();
            }
        }

        static void ShowUpdateForm()
        {
            _frmUpdate = new FrmUpdate();
            _frmUpdate.ShowInTaskbar = false;
            _frmUpdate.Show();
        }
        static void CloseUpdateForm()
        {
            _frmUpdate.Close();
        }
        static void Exit()
        {
            KillEMProcess();
            Environment.Exit(0);
        }
        private static string GerCustomerName()
        {
            string temp = list[0];
            string[] strArray = temp.Split('|');
            return strArray[4];
        }
    }
}
